package com.module.recall.dao;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import base.dao.GenericHibernateDao;
import base.util.Page;

import com.module.recall.vo.AntiFakeProductRecall;

/**
 * 商品召回数据库表处理类
 * 
 * @author wult
 * @Date Mar 2, 2012
 */
public class AntiFakeProductRecallDao extends
		GenericHibernateDao<AntiFakeProductRecall, Long> {
	private static AntiFakeProductRecallDao antiFakeProductRecallDao;

	/**
	 * 获取扫码记录单例;
	 * 
	 * @return
	 */
	public synchronized static AntiFakeProductRecallDao getInstance() {
		if (antiFakeProductRecallDao == null) {
			antiFakeProductRecallDao = new AntiFakeProductRecallDao();
		}
		return antiFakeProductRecallDao;
	}

	/**
	 * 通过antiFakeProductRecall查询出列表
	 * 
	 * @param session
	 * @param antiFakeProductRecall
	 * @param page
	 * @return
	 */

	public Page getList(Session session,
			AntiFakeProductRecall antiFakeProductRecall, Integer start,
			Integer limit) {
		Page page = new Page();
		page.setStart(start);
		page.setLimit(limit);
		String whereStr = "";
		String hql = " FROM AntiFakeProductRecall obj ";
		String hqlCount = "SELECT count(*) FROM AntiFakeProductRecall obj ";
		String split = " WHERE ";
		if (StringUtils.isNotBlank(antiFakeProductRecall.getProductName())) {
			whereStr += split + " obj.productName like '%"
					+ antiFakeProductRecall.getProductName() + "%' ";
			split = " AND ";
		}
		if (StringUtils.isNotBlank(antiFakeProductRecall.getCodeInfo())) {
			whereStr += split + " obj.codeInfo like '%"
					+ antiFakeProductRecall.getCodeInfo() + "%' ";
			split = " AND ";
		}
		if (StringUtils.isNotBlank(antiFakeProductRecall.getOrgid())) {
			whereStr += split + " obj.orgid ='"
					+ antiFakeProductRecall.getOrgid() + "' ";
			split = " AND ";
		}
		if (StringUtils.isNotBlank(antiFakeProductRecall.getRegState())) {
			whereStr += split + " obj.regState ='"
					+ antiFakeProductRecall.getRegState() + "' ";
			split = " AND ";
		}

		Query query = session.createQuery(hql + whereStr
				+ " ORDER BY obj.createtime DESC");
		query.setFirstResult(page.getStart()).setMaxResults(page.getLimit());
		page.setTotal((long) ((Long) session.createQuery(hqlCount + whereStr)
				.uniqueResult()).intValue());
		page.setRows(query.list());
		return page;
	}

	public AntiFakeProductRecall getProductRecallByCode(Session session,
			String firstCodeInfo) {
		AntiFakeProductRecall antiFakeProductRecall = null;
		List list = listByProperty(session, "codeInfo", firstCodeInfo);
		if (CollectionUtils.isNotEmpty(list)) {
			antiFakeProductRecall = (AntiFakeProductRecall) list.get(0);
		}
		return antiFakeProductRecall;
	}

}
